package RiverCrossingMinigame;

// Some code was adapted from the Virginia CS homework assignments and 
// tutorials/examples/explanations found here http://www.cs.virginia.edu/cs201j/problem-sets/ps5/

import java.awt.Color;

/**
 * Abstract class that reperesents a moveable grid object such as a player or log
 * 
 * @author Ray DeCuir
 * @version 1.0
 *
 */

public abstract class Movable {

	// The turn delay
	static final int TURN_DELAY = 500;

	// The grid used to hild the position of the object
	protected Grid grid;

	// the x and y coordinates of the object
	protected int mx;
	protected int my;

	/**
	 * This method delays the thread so that the object speed can be customized and gameplay is not too fast
	 * 
	 * @param ms The amount to delay the thread
	 */
	final public void delay(int ms)	{
		try {
			Thread.sleep(ms);
		} 
		catch (InterruptedException ie) {

		}
	}

	/** 
	 * Abstract method that moves the object within the grid
	 * 
	 */
	abstract public void executeTurn();

	
	/**
	 * Returns the color of the object, in this case green
	 * Legacy method
	 * 
	 * @return The color of the object
	 */
	public Color getColor()
	{
		return Color.green;
	} 

	/**
	 * Getter for the Grid object 
	 * 
	 * @return The grid object
	 */
	final public Grid getGrid()
	{
		return grid;
	}

	/**
	 * Getter for the x coordinate
	 * 
	 * @return The x coordinate
	 */
	final public int getX(){
		return mx;
	}

	
	/**
	 * Getter for the y coordinate
	 * 
	 * @return The y coordinate
	 */
	final public int getY(){
		return my;
	}

	
	/**
	 * Sets up a movable object to have coodinates and placement on the grid
	 * 
	 * @param x The coordinates of the object
	 * @param y The coordinates of the object
	 * @param grid The grid on which to be placed
	 */
	final public void init(int x, int y, Grid grid){
		this.mx = x;
		this.my = y;
		this.grid = grid;
	}

	/**
	 * Continuously executes the executeTurn() method to move the object about the grid. 
	 */
	public void run()
	{
		while (true) {
			executeTurn();
		}
	}

	
	/**
	 * 
	 * Moves the object to a new set of given coordinates 
	 * 
	 * @param newx The new x coordinate
	 * @param newy The new y coordinate
	 */
	synchronized public void setLocation(int newx, int newy)
	{ 
		if (grid.getObjectAt(newx, newy) != null) { 
			throw new RuntimeException();
		}

		grid.removeObjectAt(mx, my);

		try {
			grid.setObjectAt(newx, newy, this);
		} catch (Exception e) {
			throw new RuntimeException();
		}
		mx = newx;
		my = newy;
	}
}